<template>
  <div class="SearchInput">
    <van-field
      :value="value"
      @input="e=> {$emit('input', e.detail)}"
      :label="label"
      :placeholder="placeholder"
      :required="required"
      @focus="handleFocus"
    />
    <div class="search-result" v-if="isShow && searchResult.length">
      <div class="list">
        <div class="item icon-wrap">
          <i class="iconfont iconguanbi" style="color: #C4C4C4;" @click="isShow=false"></i>
        </div>
        <div class="item" v-for="item in searchResult" :key="item.id" @click="handleSelect(item)">{{ item.name }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import api from '@/api'

export default {
  props: {
    value: {
      type: String,
      required: true,
    },
    label: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    required: {
      type: Boolean,
    },
  },
  data () {
    return {
      currentValue: '',
      isShow: false,
      searchResult: [],
      active: '',
      handleSearch: debounce(this.search, 500),
    }
  },
  watch: {
    value: {
      immediate: true,
      handler () {
        this.currentValue = this.value
        this.handleSearch()
      },
    },
  },
  methods: {
    handleFocus () {
      this.isShow = true
    },
    handleSelect (item) {
      this.isShow = false
      this.$emit('input', item.name)
    },
    async search () {
      if (!this.value) {
        this.searchResult = []
        return
      }
      const { result } = await api.searchUnit({
        name: this.value,
      })
      if (result.length === 1 && result[0] === this.value) {
        return []
      }
      this.searchResult = result
    },
  },
}
</script>

<style lang="scss" scoped>
.SearchInput {
  z-index: 99;
  position: relative;
  .search-result {
    position: absolute;
    top: calc(100% - 5px);
    left: 90px;
    width: calc(100% - 110px);
    border-radius: 5px;
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(128, 128, 128, 0.35);
    .list {
      .icon-wrap {
        display: flex;
        justify-content: flex-end;
      }
      .item {
        padding: 8px;
        font-size: 16px;
        &:not(:first-child) {
          border-bottom: 1px solid #f4f2f3;
        }
      }
    }
  }
}
</style>
